<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="confirmLoading">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- 关联订单 -->
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.relatedOrder')" data-step="3"
              :data-title="$t('popup.relatedOrder')" :data-intro="$t('popup.purchaseReceiptAfterOrder')">
              <a-input-search :placeholder="$t('popup.pleaseSelectAssociated')" v-decorator="['linkNumber',validatorRules.linkNumber]"
                @search="onSearchLinkNumber" :readOnly="true" />
            </a-form-item>
          </a-col>
          <!-- 运输仓库 -->
          <!-- 验收仓库 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
              :label="$t('purchasingManagement.acceptanceWarehouse')">
              <a-select :placeholder="$t('purchasingManagement.selectAcceptanceWarehouse')"
                v-decorator="['checkDepotId', validatorRules.checkDepotId]">
                <a-select-option v-for="(item, index) in warehouseList" :key="index" :value="item.id">
                  {{ item.depotName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- 税务发票编号 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="'税务发票单号'">
              <a-input :placeholder="'请输入税务发票单号'" v-decorator.trim="[ 'billNo' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <!-- 客户 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'billNo' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.supplier')">
              <a-select :placeholder="$t('manuManagement.selectSupplier')" v-decorator="[ 'organId', validatorRules.organId ]"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addSupplier"><a-icon type="plus" /> {{$t('popup.newSupplier')}}</div>
                </div>
                <a-select-option v-for="(item,index) in supList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['billTime', validatorRules.billTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <!-- 操作按钮 -->
            <div class="action-button">
              <a-button type="primary" icon="plus" @click="handleClickAdd">{{$t('setailManagement.newlyAdded')}}</a-button>
              <span class="gap"></span>
              <a-button type="primary" icon="minus" @click="handleClear">{{$t('popup.empty')}}</a-button>
            </div>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="24">
            <j-editable-table
              :ref="refKeys[0]"
              :loading="accountTable.loading"
              :columns="accountTable.columns"
              :dataSource="accountTable.dataSource"
              :maxHeight="300"
              :rowNumber="false"
              :rowSelection="false"
              :actionButton="false"
              @valueChange="onValueChange" />
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{xs: { span: 24 },sm: { span: 24 }}" label="">
              <a-textarea :rows="2" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="[ 'remark' ]" style="margin-top:8px;"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.paymentAccount')">
              <a-select :placeholder="$t('financialManagement.selectPayment')" v-decorator="[ 'accountId', validatorRules.accountId ]"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addAccount"><a-icon type="plus" /> {{$t('popup.newAccount')}}</div>
                </div>
                <a-select-option v-for="(item,index) in accountList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.totalPayment')">
              <a-input :placeholder="$t('popup.pleaseTotalPayment')" v-decorator.trim="[ 'totalPrice' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.preferentialAmount')">
              <a-input :placeholder="$t('popup.pleaseDiscountAmount')" v-decorator.trim="[ 'discountMoney', validatorRules.discountMoney ]" @keyup="onKeyUpDiscountMoney" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.actualPayment')">
              <a-input :placeholder="$t('popup.pleaseActualPayment')" v-decorator.trim="[ 'changeAmount' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.enclosure')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="financial"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <debt-bill-list ref="debtBillList" @ok="debtBillListOk"></debt-bill-list>
    <vendor-modal ref="vendorModalForm" @ok="vendorModalFormOk"></vendor-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <person-modal ref="personModalForm" @ok="personModalFormOk"></person-modal>
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import DebtBillList from '../dialog/DebtBillList'
  import VendorModal from '../../system/modules/VendorModal'
  import AccountModal from '../../system/modules/AccountModal'
  import PersonModal from '../../system/modules/PersonModal'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { FinancialModalMixin } from '../mixins/FinancialModalMixin'
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import LinkBillList from "@/views/bill/dialog/LinkBillList"
  export default {
    name: "transportOrderModal",
    mixins: [JEditableTableMixin, FinancialModalMixin],
    components: {
      DebtBillList,
      VendorModal,
      AccountModal,
      PersonModal,
      JUpload,
      LinkBillList,
      JDate,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '1600px',
        moreStatus: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 0,
        visible: false,
        model: {},
        fileList:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['accountDataTable', ],
        activeKey: 'accountDataTable',
        accountTable: {
          loading: false,
          dataSource: [],
          columns: [
            // { title: this.$t('popup.purchaseDocumentNo'),key: 'billNumber',width: '20%', type: FormTypes.input, readonly: true },
            // { title: this.$t('popup.arrearsPayable'),key: 'needDebt', width: '10%', type: FormTypes.inputNumber, statistics: true, readonly: true },
            // { title: this.$t('popup.arrearsPaid'), key: 'finishDebt', width: '10%', type: FormTypes.inputNumber, statistics: true, readonly: true },
            // { title: this.$t('inPrint.thisPayment'),key: 'eachAmount', width: '10%', type: FormTypes.inputNumber, statistics: true, placeholder: this.$t('inPrint.pleaseTnter')+'${title}',
            //   validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe')}]
            // },
            // { title: this.$t('financialManagement.remarks'),key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'}
            { title: '产品代码',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: '产品名称',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: '尺寸',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: 'GTIN',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: 'UOM',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: '订购包装',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: '单价',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: '金额',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: '折扣金额',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: '总金额',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: '是否厂家付款',key: 'remark', width: '20%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            
          ]
        },
        confirmLoading: false,
        validatorRules:{
          organId:{
            rules: [{ required: true, message: this.$t('popup.pleaseSupplier')+'!' }]
          },
          handsPersonId:{
            rules: [{ required: true, message: this.$t('popup.pleaseSelectPersonnel')+'!' }]
          },
          billTime:{
            rules: [{ required: true, message: this.$t('popup.pleaseSelectDocumentDate')+'!' }]
          },
          accountId:{
            rules: [{ required: true, message: this.$t('popup.pleaseSelectPaymentAccount')+'!' }]
          },
          discountMoney:{
            rules: [{ required: true, message: this.$t('popup.pleaseDiscountAmount')+'!' }]
          },
          changeAmount:{
            rules: [{ required: true, message: this.$t('popup.pleaseCollectionAmount')+'!' }]
          },
          linkNumber:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectAssociated') }
            ]
          }
        },
        url: {
          add: '/accountHead/addAccountHeadAndDetail',
          edit: '/accountHead/updateAccountHeadAndDetail',
          detailList: '/accountItem/getDetailList'
        }
      }
    },
    created () {
    },
    methods: {
      onSearchLinkNumber() {
        let organId = this.form.getFieldValue('organId')
        // this.$refs.linkBillList.show('其它', this.$t('manuManagement.purchaseOrder'), this.$t('warehouseManagement.supplier'), "1,3", organId)
        this.$refs.linkBillList.show('其它', this.$t('manuManagement.purchaseOrder'), this.$t('warehouseManagement.supplier'), "1,3", organId, this.$t('purchasingManagement.purchaseOrder'))
        this.$refs.linkBillList.title = this.$t('popup.selectPurchaseOrder')
      },
      // 查询订单
      linkBillListOk(selectBillDetailRows, linkNumber, organId, discount, deposit, remark, arrivalTimeStr, depotId, deliveryMethod) {
        
        this.rowCanEdit = false
        this.materialTable.columns[1].type = FormTypes.normal
        this.changeFormTypes(this.materialTable.columns, 'preNumber', 1)
        this.changeFormTypes(this.materialTable.columns, 'finishNumber', 1)
        if (selectBillDetailRows && selectBillDetailRows.length > 0) {
          let listEx = []
          let allTaxLastMoney = 0
          for (let j = 0; j < selectBillDetailRows.length; j++) {
            let info = selectBillDetailRows[j];
            if (info.finishNumber > 0) {
              info.operNumber = info.preNumber - info.finishNumber
              info.allPrice = info.operNumber * info.unitPrice - 0
              let taxRate = info.taxRate - 0
              info.taxMoney = (info.allPrice * taxRate / 100).toFixed(2) - 0
              info.taxLastMoney = (info.allPrice + info.taxMoney).toFixed(2) - 0
            }
            info.linkId = info.id
            allTaxLastMoney += info.taxLastMoney
            listEx.push(info)
            this.changeColumnShow(info)
            // this.$nextTick(() => {
            //   this.form.setFieldsValue({
            //     'organId': organId,
            //     'arrivalTime': arrivalTimeStr,
            //   })
            // })
          }
          this.$refs.materialDataTable.getValues((error, values) => {
            let depotId = values[0].depotId
            listEx.forEach(item => {
              item.depotId = depotId
            });
            this.materialTable.dataSource = listEx
          })
          ///给优惠后金额重新赋值
          console.log(discount);
          if (allTaxLastMoney) {
            let discountMoney = (discount * allTaxLastMoney / 100).toFixed(2) - 0
            let discountLastMoney = (allTaxLastMoney - discountMoney).toFixed(2) - 0
            let changeAmount = discountLastMoney
            if (deposit) {
              this.depositStatus = true
              changeAmount = (discountLastMoney - deposit).toFixed(2) - 0
            }
            // alert(organId)
            this.$nextTick(() => {
              this.form.setFieldsValue({
                'organId': organId,
                'depotId': depotId,
                'deliveryMethod': deliveryMethod,
                'arrivalTime': arrivalTimeStr,
                'linkNumber': linkNumber,
                'discount': discount,
                'discountMoney': discountMoney,
                'discountLastMoney': discountLastMoney,
                'deposit': deposit,
                // 'changeAmount': changeAmount,
                'remark': remark
              })
            })
          }
        }
      },
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        this.billStatus = '0'
        if (this.action === 'add') {
          this.addInit("FK")
          this.fileList = []
        } else {
          this.model.billTime = this.model.billTimeStr
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'organId', 'handsPersonId', 'billTime', 'billNo', 'remark',
                  'accountId', 'totalPrice', 'discountMoney', 'changeAmount'))
          });
          
          // 加载子表数据
          let params = {
            headerId: this.model.id
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.accountTable);
        }
        this.initSupplier()
        this.initPerson()
        this.initAccount()
      },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let totalPrice = 0
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values
        billMain.type = '付款'
        for(let item of detailArr){
          totalPrice += item.eachAmount-0
        }
        billMain.totalPrice = 0-totalPrice
        billMain.changeAmount = 0-billMain.changeAmount
        // if(this.fileList && this.fileList.length > 0) {
        //   billMain.fileName = this.fileList
        // }
        if(this.model.id){
          billMain.id = this.model.id
        }
        billMain.status = this.billStatus
        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      },
      handleClickAdd() {
        let organId = this.form.getFieldValue('organId')
        if(organId){
          this.$refs.debtBillList.show(organId, this.$t('purchasingManagement.warehousing'), this.$t('purchasingManagement.purchase'), this.$t('purchasingManagement.supplier'), "", this.$t('warehouseManagement.other'), this.$t('otherJS.chargeConfirmation'))
          this.$refs.debtBillList.title = this.$t('popup.selectReceiptDoc')
        } else {
          this.$message.warning(this.$t('popup.pleaseSupplier')+'!');
        }
      },
      handleClear() {
        this.accountTable.dataSource = []
      }
    }
  }
</script>
<style scoped>
  .action-button {
    margin-bottom: 8px;
  }
  .gap {
    padding-left: 8px;
  }
</style>